<?php
namespace Swiftx\Bundle\WeChat\Controller\ClientApi;
use Swiftx\Bundle\WeChat\Controller\Mall\Goods;
use Swiftx\Bundle\WeChat\Interfaces\Common\AjaxController;
use Swiftx\Bundle\WeChat\Interfaces\Controller\ClientApi\AppLie as AppLieInterface;
use Swiftx\Bundle\WeChat\Model\Client\AppLie as AppLieModel;
use Swiftx\Bundle\WeChat\Model\Mall\Goods as GoodsModel;
use Swiftx\Bundle\WeChat\Model\Seller\Company;
use Swiftx\Interfaces\Httpd\Request;
use Swiftx\Interfaces\Httpd\Response;

/**
 * 用户登录页面实现
 */
class AppLie extends AjaxController implements AppLieInterface {

    /**
     * 查询当前小程序
     * @param Request $request
     * @return AppLieModel
     * @throws \ErrorException
     */
    protected function currentAppLie(Request $request):AppLieModel{
        if(!$request->hasParam('appID'))
            throw new \ErrorException('参数不全！');
        /** @var AppLieModel $appLie */
        $appLie = $this->entityManager->fetch(
            AppLieModel::class,
            $request->getParam('appID')
        );
        return $appLie;
    }

    /**
     * 获取当前所属公司
     * @param Request $request
     * @return Company
     */
    protected function currentCompany(Request $request):Company{
        return $this->currentAppLie($request)->getCompany();
    }

    /**
     * 前端用户登陆
     * @param Request   $request
     * @param Response  $response
     * @router method   get
     * @return bool
     */
    public function userLogin(Request $request, Response $response):bool{
        $company = $this->currentCompany($request);
        // 响应查询结果
        return $this->successDisplay($response, [
            'title' => $company->getTitle(),
            'introduce' => $company->getIntroduce()
        ]);
    }

    /**
     * 获取店铺信息
     * @param Request   $request
     * @param Response  $response
     * @router method   get
     * @return bool
     */
    public function storeInfo(Request $request, Response $response):bool{
        $company = $this->currentCompany($request);
        // 响应查询结果
        return $this->successDisplay($response, [
            'title' => $company->getTitle(),
            'introduce' => $company->getIntroduce()
        ]);
    }

    /**
     * 显示商品列表
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    public function goodsList(Request $request, Response $response):bool{
        $company = $this->currentCompany($request);
        $query = $this->entityManager->builder(GoodsModel::class);
        $query->conditionEqualString('company', $company->getID());
        $query->conditionEqualLtInt('sellTime', time());

        // 设置查询关键词
        $keyword = $request->getParam('keyword');
        if(!empty($keyword))
            $query->conditionLike('title', '%'.$keyword.'%');

        // 分页数据条件
        $currentPage = $request->getParam('page', 1);
        $capacity = $request->getParam('capacity', 20);

        $page = $query->page($currentPage, $capacity);
        $result['list'] = [];
        $result['total'] = $page->getTotal();

        /** @var GoodsModel $goods */
        foreach ($page->getData() as $goods){
            $result['list'][] = [
                'id' => $goods->getID(),
                'title' => $goods->getTitle(),
                'image' => $goods->getImage()->getUrl(),
                'stock' => $goods->getStock(),
                'price' => [
                    'max' => $goods->getMaxPrice(),
                    'min' => $goods->getMinPrice()
                ],
                'time' => $goods->getCreateTimeFormat()
            ];
        }

        // 响应查询结果
        return $this->successDisplay($response, $result);
    }

    /**
     * 获取商品详细
     * @param Request   $request
     * @param Response  $response
     * @router method   get
     * @return bool
     */
    public function goodsInfo(Request $request, Response $response):bool{
        if(!$request->hasParam('id'))
            return $this->errorDisplay($response, '参数不全！');
        $company = $this->currentCompany($request);
        /** @var GoodsModel $goods */
        $goods = $this->entityManager->fetch(GoodsModel::class, $request->getParam('id'));
        if(empty($goods) || $company->getID() != $goods->getCompanyID())
            return $this->errorDisplay($response, '商品不存在！');
        $goodsInfo = [
            'id' => $goods->getID(),
            'title' => $goods->getTitle(),
            'images' => [],
            'stock' => $goods->getStock(),
            'specs' => [],
            'price' => [
                'max' => $goods->getMaxPrice(),
                'min' => $goods->getMinPrice()
            ],
            'time' => $goods->getCreateTimeFormat()
        ];
        foreach ($goods->getImages() as $image)
            $goodsInfo['images'][] = $image->getUrl();
        foreach ($goods->getSpecs() as $spec)
            $goodsInfo['specs'][] = [
                'id' => $spec->getID(),
                'name' => $spec->getName(),
                'price' => $spec->getPrice(),
                'stock' => $spec->getStock()
            ];
        foreach ($goods->getAttributes() as $attribute)
            $goodsInfo['attribute'][] = [
                'name' => $attribute->getName(),
                'value' => $attribute->getValue()
            ];
        return $this->successDisplay($response, $goodsInfo);
    }

}